﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace WXY.Course.Common.Authorization
{
    public class DefaultAuthorization
    {
        public static void SetAuthorized(string userName)
        {
            if (userName == null) throw new HttpException("there is no user login");

            SetAuthCookie(userName);
        }

        public static string GetUser()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

            if (cookie == null) return null;

            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

            return ticket.Name;
        }

        private static void SetAuthCookie(string userName)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, true, (int)FormsAuthentication.Timeout.TotalMinutes);

            string encTicket = FormsAuthentication.Encrypt(ticket);

            if (string.IsNullOrEmpty(encTicket))
            {
                throw new HttpException("Unable_to_encrypt_cookie_ticket");
            }

            HttpCookie oldCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (oldCookie != null)
            {
                oldCookie.Expires = DateTime.Now.AddYears(-1);

                HttpContext.Current.Response.Cookies.Set(oldCookie);
            }

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            string cookieDomain = FormsAuthentication.CookieDomain;
            if (!string.IsNullOrEmpty(cookieDomain))
            {
                cookie.Domain = cookieDomain;
            }
            string strCookiePath = FormsAuthentication.FormsCookiePath;
            cookie.HttpOnly = true;
            cookie.Path = strCookiePath;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Expires = ticket.Expiration;

            HttpContext.Current.Response.Cookies.Set(cookie);
        }

        public static void LogOut()
        {
            FormsAuthentication.SignOut();
        }

    }
}
